package eureka.ui.book;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eureka.domain.book.BasicBookItem;
import eureka.domain.book.BookItem;
import eureka.domain.book.BookState;
import eureka.exceptions.DatabaseException;
import eureka.service.book.IBookService;
import eureka.service.book.impl.BookService;
import util.lang.RefValue;
import util.web.page.PageBean;

/**
 * Servlet implementation class ShowBasicBook
 */
@WebServlet("/Books/ShowBasicBook")
public class ShowBasicBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IBookService ibs = new BookService();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ShowBasicBook() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String bbIDstr = request.getParameter("bbid");
		String curPagestr = request.getParameter("page");
		String pageSizestr = request.getParameter("pageSize");

		long bbID = 1;
		long curPage = 1;
		long pageSize = 20;
		try {
			bbID = Long.parseLong(bbIDstr);

		} catch (NumberFormatException e) {
			response.sendError(404);
			return;
		}

		try {
			curPage = Long.parseLong(curPagestr);
			if (curPage <= 0)
				curPage = 1;
		} catch (NumberFormatException e) {
			curPage = 1;
		}
		try {
			pageSize = Long.parseLong(pageSizestr);
			if (pageSize < 0) {
				pageSize = 20;
			}
			if (pageSize > 100) {
				pageSize = 100;
			}
		} catch (NumberFormatException e) {
			pageSize = 20;
		}

		PageBean<BookItem> biPage = new PageBean<BookItem>();
		biPage.setCurrentPage(curPage);
		biPage.setPageSize(pageSize);

		RefValue<Long> count = new RefValue<Long>();

		BasicBookItem basicbookitem = null;
		try {
			basicbookitem = ibs.getBasicBookByBbID(bbID);
			if (basicbookitem == null) {
				response.sendError(404);
				return;
			}
			List<BookItem> list = ibs.searchBooks("", bbID,0, BookState.OnShelf,
					biPage.getRecordStart(), biPage.getPageSize(), count);
			biPage.setRecords(list, count.getValue());
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}

		request.setAttribute("page", biPage);
		request.setAttribute("basicbookitem", basicbookitem);
		request.getRequestDispatcher("listbook.jsp").forward(request, response);
	}

}
